package com.kstech.mp3604.utils;

import android.os.Build;

import java.io.DataOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SystemTimeUtil {
    private String mDateTime = "2021-04-22_11:30:00";


    /**
     * 接收的时间格式: 2021-04-22_11:30:00
     */
    public static void setSystemTime(String dateTime) {
        DateFormat parseFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
        DataOutputStream dos = null;
        try {
            Date date = parseFormat.parse(dateTime);
//            Process process1 = Runtime.getRuntime().exec("su");
            Process process = Runtime.getRuntime().exec("su");
            dos = new DataOutputStream(process.getOutputStream());
            if (Build.VERSION.SDK_INT >= 25) {
                dateTime = new SimpleDateFormat("MMddHHmmyyyy.ss").format(date); //Android 7.1
                dos.writeBytes("date " + dateTime + "\n");
                dos.writeBytes("busybox hwclock -w \n");
                dos.writeBytes("exit\n");
                dos.flush();

            } else {
                dateTime = new SimpleDateFormat("yyyyMMdd.HHmmss").format(date); //低于Android 7.1
                dos.writeBytes("date -s " + dateTime + "\n");
                dos.writeBytes("clock -w\n");
                dos.writeBytes("exit\n");
                dos.flush();

            }
        } catch (Exception e) {
            //            mSyncTimeCallBack.onFailed();
            e.printStackTrace();
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
